<?php

namespace App\Http\Controllers\Wechat\WechatServiceAccount;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\SimpleCart;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\WechatServiceAccountAddress;
use App\Models\Product;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Services\Wechat\WechatPaymentService;

class CheckoutController extends Controller
{
    /**
     * 展示结算页面
     */
    public function show(Request $request)
    {
        if (!auth('wechat')->check()) {
            return redirect()->route('wechat.service.account.login');
        }
        $userId = auth('wechat')->id();
        $productTotalPrice = 0;
        $cartData = [];
        $isDirectBuy = false;
        $directBuyProduct = null;
        
        // 检查是否是直接购买模式
        if ($request->has('direct_buy') && $request->has('product_id')) {
            $isDirectBuy = true;
            $productId = $request->input('product_id');
            $quantity = max(1, (int)$request->input('quantity', 1));
            $variantId = $request->input('variant_id');
            
            // 获取商品信息
            $product = Product::find($productId);
            if ($product) {
                // 计算小计金额
                $subtotal = $product->price * $quantity;
                
                // 确保product对象可以正确序列化为JSON
                $productArray = [
                    'id' => $product->id,
                    'name' => $product->name,
                    'price' => $product->price,
                    'image_url' => $product->image_url ?? '/images/default-product.jpg',
                    'description' => $product->description ?? '',
                    'stock' => $product->stock ?? 0
                ];
                
                $directBuyProduct = [
                    'id' => 'direct_' . $productId, // 使用特殊ID标识直接购买
                    'product' => $productArray,
                    'quantity' => $quantity,
                    'subtotal' => $subtotal,
                    'variant_id' => $variantId
                ];
                
                $productTotalPrice = $subtotal;
                // 只包含直接购买的商品，使用赋值而非追加
                $cartData = [$directBuyProduct];
            }
        } else {
            // 只有在非直接购买模式下才显示购物车商品
            $cartItems = SimpleCart::where('user_id', $userId)->with('product')->get();
            foreach ($cartItems as $item) {
                if ($item->product) {
                    $subtotal = $item->product->price * $item->quantity;
                    $cartData[] = [
                        'id' => $item->id,
                        'product' => $item->product,
                        'quantity' => $item->quantity,
                        'subtotal' => $subtotal,
                        'variant_id' => $item->variant_id ?? null
                    ];
                    $productTotalPrice += $subtotal;
                }
            }
        }
        
        // 获取运费商品信息
        $shippingProduct = Product::find(1);
        $shippingFee = $shippingProduct ? $shippingProduct->price : 0;
        $freeShippingThreshold = config('ecommerce.free_shipping_threshold', 60);
        $isFreeShipping = $productTotalPrice >= $freeShippingThreshold;
        $actualShippingFee = $isFreeShipping ? 0 : $shippingFee;
        $totalPrice = $productTotalPrice + $actualShippingFee;
        
        // 获取用户的所有收货地址
        $userAddresses = WechatServiceAccountAddress::where('user_id', $userId)
            ->orderByDesc('is_default')
            ->latest()
            ->get();
        
        // 记录日志以便调试
        if ($isDirectBuy && $directBuyProduct) {
            Log::info('传递给视图的直接购买商品数据', ['directBuyProduct' => $directBuyProduct]);
        }
        
        return view('wechat.service_account.checkout', [
            'cartData' => $cartData, 
            'productTotalPrice' => $productTotalPrice, 
            'totalPrice' => $totalPrice, 
            'userAddresses' => $userAddresses,
            'shippingFee' => $shippingFee,
            'actualShippingFee' => $actualShippingFee,
            'isFreeShipping' => $isFreeShipping,
            'freeShippingThreshold' => $freeShippingThreshold,
            'isDirectBuy' => $isDirectBuy,
            'directBuyProduct' => $directBuyProduct,
            'pageType' => $isDirectBuy ? 'direct_buy' : 'cart_checkout'
        ]);
    }

    /**
     * 提交订单
     */
    public function submit(Request $request, WechatPaymentService $paymentService)
    {
        Log::info('进入submit方法');
        if (!auth('wechat')->check()) {
            Log::warning('用户未登录，重定向到登录页');
            return redirect()->route('wechat.service.account.login');
        }
        $userId = auth('wechat')->id();
        Log::info('用户已登录', ['user_id' => $userId]);
        $validated = $request->validate([
            'receiver_name' => 'required|string|max:20',
            'receiver_address' => 'required|string|max:100',
            'receiver_phone' => 'required|string|max:20',
        ]);
        Log::info('表单校验通过', $validated);
        
        $isDirectBuy = $request->input('direct_buy', false);
        $productTotalPrice = 0;
        $orderItemsData = [];
        
        Log::info('订单提交请求分析', ['is_direct_buy' => $isDirectBuy, 'request_data' => $request->all()]);
        
        if ($isDirectBuy) {
            Log::info('处理直接购买模式订单');
            
            // 从多个可能的来源获取商品ID
            $productId = $request->input('product_id');
            
            // 如果没获取到，尝试从POST数据的其他位置查找
            if (!$productId) {
                Log::warning('尝试从其他位置获取商品ID', ['post_data' => $request->post()]);
                // 尝试直接从POST数据中获取
                $postData = $request->post();
                if (isset($postData['product_id'])) {
                    $productId = $postData['product_id'];
                }
            }
            
            // 再次检查
            if (!$productId) {
                Log::error('无法获取直接购买的商品ID', ['request_data' => $request->all()]);
                return response()->json([
                    'success' => false,
                    'message' => '无法获取商品信息，请返回重试',
                ]);
            }
            
            Log::info('直接购买获取到商品ID', ['product_id' => $productId]);
            
            $quantity = max(1, (int)$request->input('quantity', 1));
            $variant = $request->input('variant_id');
            
            // 获取商品信息
            $product = Product::find($productId);
            if (!$product) {
                Log::warning('直接购买的商品不存在', ['product_id' => $productId]);
                return response()->json([
                    'success' => false,
                    'message' => '商品信息错误，请重新选择',
                ]);
            }
            
            // 检查库存
            if ($quantity > $product->stock) {
                Log::warning('直接购买数量超过库存', ['product_id' => $productId, 'quantity' => $quantity, 'stock' => $product->stock]);
                return response()->json([
                    'success' => false,
                    'message' => '购买数量超过库存',
                ]);
            }
            
            $productTotalPrice = $product->price * $quantity;
            $orderItemsData[] = [
                'product_id' => $product->id,
                'product_name' => $product->name,
                'quantity' => $quantity,
                'price' => $product->price,
                'variant_id' => $variant
            ];
        } else {
            // 普通购物车结算模式
            $cartItems = SimpleCart::where('user_id', $userId)->with('product')->get();
            Log::info('购物车商品', ['count' => $cartItems->count(), 'items' => $cartItems->toArray()]);
            if ($cartItems->isEmpty()) {
                Log::warning('购物车为空，无法下单');
                return response()->json([
                    'success' => false,
                    'message' => '购物车为空，无法下单',
                ]);
            }
            
            foreach ($cartItems as $item) {
                if ($item->product) {
                    $productTotalPrice += $item->product->price * $item->quantity;
                    $orderItemsData[] = [
                        'product_id' => $item->product->id,
                        'product_name' => $item->product->name,
                        'quantity' => $item->quantity,
                        'price' => $item->product->price,
                        'variant_id' => $item->variant_id ?? null
                    ];
                }
            }
        }
        
        // 计算运费
        $shippingProduct = Product::find(1);
        $shippingFee = $shippingProduct ? $shippingProduct->price : 0;
        $freeShippingThreshold = config('ecommerce.free_shipping_threshold', 60);
        $isFreeShipping = $productTotalPrice >= $freeShippingThreshold;
        $actualShippingFee = $isFreeShipping ? 0 : $shippingFee;
        $totalPrice = $productTotalPrice + $actualShippingFee;
        Log::info('计算总价', ['total_price' => $totalPrice, 'product_total' => $productTotalPrice, 'shipping_fee' => $actualShippingFee, 'is_free_shipping' => $isFreeShipping]);
        DB::beginTransaction();
        try {
            Log::info('准备写入订单');
            // 生成符合要求的订单编号
            do {
                $orderNumber = date('YmdHis') . mt_rand(1000, 9999);
            } while (Order::where('order_number', $orderNumber)->exists());
            
            $order = Order::create([
                'order_number' => $orderNumber,
                'wechat_service_account_user_id' => $userId,
                'receiver_name' => $request->receiver_name,
                'receiver_phone' => $request->receiver_phone,
                'shipping_address' => $request->receiver_address,
                'total_price' => $totalPrice,
                'status' => '未支付',
            ]);
            Log::info('订单写入成功', ['order_id' => $order->id]);
            // 创建订单项
            foreach ($orderItemsData as $itemData) {
                OrderItem::create([
                    'order_id' => $order->id,
                    'product_id' => $itemData['product_id'],
                    'product_name' => $itemData['product_name'],
                    'quantity' => $itemData['quantity'],
                    'price' => $itemData['price'],
                    'variant' => $itemData['variant_id'] ?? null,
                ]);
            }
            
            // 只有在非直接购买模式下才清空购物车
            if (!$isDirectBuy) {
                SimpleCart::where('user_id', $userId)->delete();
            }
            DB::commit();
            Log::info('下单流程完成，准备调用支付服务');
            
            // 获取用户openid
            $user = auth('wechat')->user();
            if (!$user || !$user->openid) {
                Log::error('无法获取用户openid', ['user_id' => $userId]);
                return response()->json([
                    'success' => false,
                    'message' => '无法获取支付信息，请重试',
                ]);
            }
            $openid = $user->openid;

            try {
                // 调用支付服务生成支付参数
                $paymentParams = $paymentService->createOrder([
                    'out_trade_no' => $order->order_number,
                    'total_amount' => $totalPrice * 100, // 改为total_amount
                    'description' => ' Oasis Garden 商品购买', // 改为description
                    'openid' => $openid
                ]);

                Log::info('微信支付返回', $paymentParams);
                if (isset($paymentParams['prepay_id'])) {
                    Log::info('支付参数生成成功', ['order_id' => $order->id]);
                    return response()->json([
                        'success' => true,
                        'message' => '下单成功！',
                        'order_id' => $order->id,
                        'order_number' => $order->order_number,
                        'total_price' => $totalPrice,
                        'prepay_id' => $paymentParams['prepay_id']
                    ]);
                } else {
                    Log::error('下单失败，返回错误信息', $paymentParams);
                    $errorMsg = isset($paymentParams['error']) ? $paymentParams['error'] : json_encode($paymentParams, JSON_UNESCAPED_UNICODE);
                    return response()->json([
                        'success' => false,
                        'message' => '支付参数生成失败：' . $errorMsg,
                    ]);
                }
            } catch (\Exception $e) {
                Log::error('支付服务调用异常: ' . $e->getMessage(), ['trace' => $e->getTraceAsString()]);
                return response()->json([
                    'success' => false,
                    'message' => '支付服务暂时不可用，请稍后重试',
                ]);
            }
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('下单异常: ' . $e->getMessage(), ['trace' => $e->getTraceAsString()]);
            return response()->json([
                'success' => false,
                'message' => '下单失败，请重试',
            ], 500);
        }
    }

    /**
     * 获取JSAPI支付配置
     */
    public function getJsConfig(Request $request, WechatPaymentService $paymentService)
    {
        $request->validate([
            'prepay_id' => 'required|string',
        ]);

        try {
            $prepayId = $request->input('prepay_id');
            $jsConfig = $paymentService->generateJsConfig($prepayId);

            Log::info('JSAPI配置生成成功', [
                'prepay_id' => $prepayId,
                'js_config' => $jsConfig
            ]);

            return response()->json([
                'success' => true,
                'js_config' => $jsConfig
            ]);
        } catch (\Exception $e) {
            Log::error('JSAPI配置生成失败', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            return response()->json([
                'success' => false,
                'message' => '支付配置生成失败：' . $e->getMessage(),
            ]);
        }
    }
}